import { useState, useEffect, useRef } from "react";
import "./App.css";

import QRCodeStyling from "qr-code-styling";

const qrCode = new QRCodeStyling({
    width: 800,
    height: 800,
    image: "",
    dotsOptions: {
        color: "#4267b2",
        type: "rounded",
    },
    imageOptions: {
        crossOrigin: "anonymous",
        margin: 20,
    },
});

export default function App() {
    const [url, setUrl] = useState("https://simcn.gitee.io/fedtools/qrcode");
    const ref = useRef(null);

    useEffect(() => {
        qrCode.append(ref.current);
    }, []);

    useEffect(() => {
        qrCode.update({
            data: url,
        });
    }, [url]);

    const onUrlChange = (event) => {
        event.preventDefault();
        setUrl(event.target.value);
    };

    const onDownloadClick = () => {
        qrCode.download({
            extension: "png",
        });
    };

    return (
        <div className="App">
            <div style={styles.inputWrapper}>
                <input
                    value={url}
                    onChange={onUrlChange}
                    style={styles.inputBox}
                />
            </div>
            <div ref={ref} />
            <div>
                <button onClick={onDownloadClick}>下载二维码</button>
            </div>
        </div>
    );
}

const styles = {
    inputWrapper: {
        margin: "20px",
        display: "flex",
        justifyContent: "space-between",
        width: "100%",
    },
    inputBox: {
        flexGrow: 1,
        marginRight: 20,
    },
};

